﻿using CommonLib.Base;
using CommonLib.CodeEntity;
using System.Text.RegularExpressions;

namespace SQLServer.Convert;

public class SelectConvert(SelectCodeEntity sel) : BaseConvert
{

    private readonly SelectCodeEntity Sel = sel;

    protected override List<string> Run()
    {
        var list = new List<string>() { "SELECT" };
        foreach (var item in Sel.Colums)
        {
            list.Add($"{item.SqlLine()},");
        }
        list[^1] = list[^1].TrimEnd(',');
        if (Sel.Into > 0) list.Insert(Sel.Into, "INTO");
        list.Add("FROM");
        var ntbl = new List<string>();
        var jtbl = new List<string>();
        foreach (var item in Sel.Tables)
        {
            var line = item.SqlLine();
            if (line.Contains(" JOIN ")) jtbl.Add(line);
            else ntbl.Add(item.SqlLine());
        }

        var cons = new List<string>();
        var joins = new List<string>();
        foreach (var item in Sel.Conditions)
        {
            var line = item.SqlLine();
            if (line.Contains('÷')) joins.Add(line);
            else cons.Add(line);
        }
        if (jtbl.Count > 0 && ntbl.Count == 0)
        {
            list.AddRange(jtbl);
            list.AddRange(cons);
        }
        else if (joins.Count > 0)
        {
            var sub = new List<string>();
            foreach (var item in joins)
            {
                var mats = Regex.Matches(item, "[A-Z0-9]+÷[A-Z0-9]+");
                sub.AddRange(mats.Select(m => m.Value));
            }
        }
 
        if (Sel.Union != null)
        {
            list.Add(Sel.Ustr!);
            list.AddRange(Sel.Union.SqlList());
        }
        if (Sel.End != null) list.Add(Sel.End);
        return list;
    }
}
